package com.wyzz.hr.util;

import java.math.BigDecimal;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.util.*;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;

import com.wyzz.hr.base.Constants;

public class StringUtil {

	public StringUtil() {
	}

	public static String md5(String str) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
			byte b[] = md.digest();
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < b.length; i++) {
				int v = b[i];
				v = v >= 0 ? v : 256 + v;
				String cc = Integer.toHexString(v);
				if (cc.length() == 1)
					sb.append('0');
				sb.append(cc);
			}

			return sb.toString();
		} catch (Exception e) {
			return "";
		}
	}

	public static String encodePassword(String password) {
		byte unencodedPassword[] = password.getBytes();
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			e.printStackTrace();
		}
		md.reset();
		md.update(unencodedPassword);
		byte encodedPassword[] = md.digest();
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < encodedPassword.length; i++) {
			if ((encodedPassword[i] & 0xff) < 16)
				buf.append("0");
			buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
		}

		return buf.toString();
	}

	public static String[][] merge2D(String twoDArray1[][],
			String twoDArray2[][]) {
		int size1 = 0;
		int size2 = 0;
		if (twoDArray1 != null)
			size1 = twoDArray1.length;
		if (twoDArray2 != null)
			size2 = twoDArray2.length;
		if (size1 + size2 == 0)
			return (String[][]) null;
		String merge2DArray[][] = new String[size1 + size2][2];
		for (int i = 0; i < size1; i++) {
			merge2DArray[i][0] = twoDArray1[i][0];
			merge2DArray[i][1] = twoDArray1[i][1];
		}

		for (int i = 0; i < size2; i++) {
			merge2DArray[i + size1][0] = twoDArray2[i][0];
			merge2DArray[i + size1][1] = twoDArray2[i][1];
		}

		return merge2DArray;
	}

	public static String[][] merge(String sourceArray[][]) {
		return sourceArray;
	}

	public static String[] merge(String sourceArray[]) {
		return sourceArray;
	}

	public static String[] convert2DTo1D(String twoDArray[][]) {
		if (twoDArray == null)
			return null;
		String result[] = new String[twoDArray.length];
		for (int i = 0; i < twoDArray.length; i++)
			result[i] = twoDArray[i][0];

		return result;
	}

	public static String[] merge1D(String oneDArray1[], String oneDArray2[]) {
		int size1 = 0;
		int size2 = 0;
		if (oneDArray1 != null)
			size1 = oneDArray1.length;
		if (oneDArray2 != null)
			size2 = oneDArray2.length;
		String merge1DArray[] = new String[size1 + size2];
		for (int i = 0; i < size1; i++)
			merge1DArray[i] = oneDArray1[i];

		for (int i = 0; i < size2; i++)
			merge1DArray[i + size1] = oneDArray2[i];

		return merge1DArray;
	}

	public static String[] merge1D(String oneDArray1[], String stringToMerge) {
		String result[];
		if (oneDArray1 == null) {
			result = new String[1];
			result[0] = new String(stringToMerge);
			return result;
		}
		result = new String[oneDArray1.length + 1];
		for (int i = 0; i < oneDArray1.length; i++)
			result[i] = oneDArray1[i];

		result[oneDArray1.length] = stringToMerge;
		return result;
	}

	public static String splitForIn(String oneDArray[]) {
		if (oneDArray == null || oneDArray.length == 0)
			return null;
		StringBuffer idStr = new StringBuffer("");
		String arr$[] = oneDArray;
		int len$ = arr$.length;
		for (int i$ = 0; i$ < len$; i$++) {
			String str = arr$[i$];
			if (!StringUtils.isEmpty(str))
				idStr.append("'").append(str).append("',");
		}

		return idStr.substring(0, idStr.length() - 1);
	}

	public static Set authStringToSet(String auth) {
		Set authSet = new HashSet();
		if (auth == null)
			return authSet;
		String auths[] = auth.split(",");
		for (int i = 0; i < auths.length; i++)
			authSet.add(Integer.valueOf(Integer.parseInt(auths[i])));

		return authSet;
	}

	public static String authArrToString(Integer auth[]) {
		if (auth == null || auth.length == 0)
			return "";
		String authString = "";
		for (int i = 0; i < auth.length; i++)
			authString = (new StringBuilder()).append(authString).append(
					auth[i]).append(",").toString();

		return authString.substring(0, authString.length() - 1);
	}

	public static String authSetToType(Set authSet) {
		int suthSetSize = authSet.size();
		if (authSet.removeAll(Constants.ADM_AUTHS)
				|| authSet.size() < suthSetSize)
			return "USERADM";
		if (authSet.removeAll(Constants.MGR_AUTHS)
				|| authSet.size() < suthSetSize)
			return "USERMGR";
		else
			return "USEREMP";
	}

	public static String authStringToType(String auth) {
		Set authSet = authStringToSet(auth);
		return authSetToType(authSet);
	}

	public static String message(String message, Object variables[]) {
		String output = MessageFormat.format(message, variables);
		return output;
	}

	public static String formatBDToS(BigDecimal value, String format[]) {
		if (value == null)
			return null;
		String DCformat = "##########0.00";
		if (format.length > 0 && !StringUtils.isEmpty(format[0]))
			DCformat = format[0];
		DecimalFormat decimalFormat = new DecimalFormat(DCformat);
		return decimalFormat.format(value);
	}

	public static String getClassName(Object obj) {
		if (obj == null) {
			return null;
		} else {
			String className = obj.getClass().getName();
			int index = className.lastIndexOf(".");
			return className.substring(index + 1);
		}
	}

	public static String getClassNameLowCase(Object obj) {
		return getClassName(obj).toLowerCase();
	}

	public static String messageNoErrCode(String message, Object variables[]) {
		String output = MessageFormat.format(message, variables);
		int index = output.indexOf(":");
		if (index >= 0 && index <= 16)
			return output.substring(index + 1);
		else
			return output;
	}

	public static boolean isNumber(String value) {
		if (StringUtils.isEmpty(value)) {
			return false;
		} else {
			Pattern pattern = Pattern.compile("[0-9]*");
			return pattern.matcher(value).matches();
		}
	}

	public static boolean isMobile(String value) {
		if (StringUtils.isEmpty(value))
			return false;
		if (!isNumber(value))
			return false;
		if (value.charAt(0) == '0')
			return true;
		if (value.charAt(0) != '1') {
			return false;
		} else {
			String style = "^(13[0-9]|15[0|3|6|7|8|9]|18[7|8|9])\\d{8}$";
			return value.matches(style);
		}
	}

	public static boolean isPhone(String value) {
		if (StringUtils.isEmpty(value) || value.trim().length() < 6) {
			return false;
		} else {
			String partten = "^([-0|1|2|3|4|5|6|7|8|9|+|.|#|*|(|)]){7,}$";
			return value.matches(partten);
		}
	}

	public static boolean isFloat(String value, Integer length[]) {
		if (StringUtils.isEmpty(value))
			return false;
		String style = "^(\\-)?\\d{1,";
		if (length.length != 0 && length[0].intValue() > 1)
			style = (new StringBuilder()).append(style).append(length[0])
					.toString();
		style = (new StringBuilder()).append(style).append("}(\\.\\d{1,")
				.toString();
		if (length.length > 1 && length[1].intValue() > 1)
			style = (new StringBuilder()).append(style).append(length[1])
					.toString();
		style = (new StringBuilder()).append(style).append("})?$").toString();
		return value.matches(style);
	}

	public static String addSegmentToShift(String sessionStr, String cut) {
		if (StringUtils.isEmpty(sessionStr))
			return cut;
		List timeList = new ArrayList();
		String sessionArr[] = sessionStr.split(",");
		for (int i = 0; sessionArr != null && i < sessionArr.length; i++)
			timeList.add(sessionArr[i]);

		String cutArr[] = cut.split("-");
		String cutStart = cutArr[0];
		String cutEnd = cutArr[1];
		if (timeToMin(cutEnd) < timeToMin(((String) timeList.get(0)).split("-")[0])) {
			timeList.add(0, cut);
			return concatStr(timeList, ",");
		}
		if (timeToMin(cutEnd) == timeToMin(((String) timeList.get(0))
				.split("-")[0])) {
			timeList.set(0, (new StringBuilder()).append(cutStart).append("-")
					.append(((String) timeList.get(0)).split("-")[1])
					.toString());
			return concatStr(timeList, ",");
		}
		if (timeToMin(((String) timeList.get(timeList.size() - 1)).split("-")[1]) == timeToMin(cutStart)) {
			timeList.set(timeList.size() - 1, (new StringBuilder()).append(
					((String) timeList.get(timeList.size() - 1)).split("-")[0])
					.append("-").append(cutEnd).toString());
			return concatStr(timeList, ",");
		}
		if (timeToMin(((String) timeList.get(timeList.size() - 1)).split("-")[1]) < timeToMin(cutStart)) {
			timeList.add(timeList.size(), cut);
			return concatStr(timeList, ",");
		}
		int i = 1;
		do {
			if (i >= timeList.size())
				break;
			String tempCut = (String) timeList.get(i);
			String tempCutStart = tempCut.split("-")[0];
			String tempCutEnd = tempCut.split("-")[1];
			String lastCut = (String) timeList.get(i - 1);
			String lastCutStart = lastCut.split("-")[0];
			String lastCutEnd = lastCut.split("-")[1];
			if (timeToMin(cutStart) <= timeToMin(tempCutStart)) {
				if (timeToMin(cutStart) == timeToMin(lastCutEnd)
						&& timeToMin(cutEnd) != timeToMin(tempCutStart)) {
					timeList
							.set(i - 1, (new StringBuilder()).append(
									lastCutStart).append("-").append(cutEnd)
									.toString());
					return concatStr(timeList, ",");
				}
				if (timeToMin(cutStart) != timeToMin(lastCutEnd)
						&& timeToMin(cutEnd) == timeToMin(tempCutStart)) {
					timeList.set(i, (new StringBuilder()).append(cutStart)
							.append("-").append(tempCutEnd).toString());
					return concatStr(timeList, ",");
				}
				if (timeToMin(cutStart) == timeToMin(lastCutEnd)
						&& timeToMin(cutEnd) == timeToMin(tempCutStart)) {
					timeList.set(i - 1, (new StringBuilder()).append(
							lastCutStart).append("-").append(tempCutEnd)
							.toString());
					timeList.remove(i);
					return concatStr(timeList, ",");
				}
				timeList.add(i, cut);
				break;
			}
			i++;
		} while (true);
		return concatStr(timeList, ",");
	}

	public static int timeToMin(String time) {
		String timeArr[] = time.split(":");
		return Integer.parseInt(timeArr[0]) * 60 + Integer.parseInt(timeArr[1]);
	}

	public static String concatStr(List stringList, String delimit) {
		StringBuffer resultBuf = new StringBuffer("");
		for (int i = 0; i < stringList.size(); i++)
			resultBuf.append((new StringBuilder()).append(
					(String) stringList.get(i)).append(delimit).toString());

		if (!StringUtils.isEmpty(resultBuf.toString()))
			return resultBuf
					.substring(0, resultBuf.length() - delimit.length());
		else
			return resultBuf.toString();
	}

	public static String addConcatStr(String concatStr, String delimit,
			Object newStrings[]) {
		StringBuffer resultBuf = new StringBuffer(concatStr);
		if (newStrings == null || newStrings.length == 0)
			return concatStr;
		for (int i = 0; i < newStrings.length; i++)
			resultBuf.append((new StringBuilder()).append(delimit).append(
					newStrings[i]).toString());

		if (StringUtils.isEmpty(resultBuf.toString()))
			return concatStr;
		if (StringUtils.isEmpty(concatStr))
			return resultBuf
					.substring(0 + delimit.length(), resultBuf.length());
		else
			return resultBuf.toString();
	}

	public static String cutSegmentFromShift(String sessionStr, String cut) {
		if (StringUtils.isEmpty(sessionStr))
			return sessionStr;
		if (StringUtils.isEmpty(cut))
			return sessionStr;
		String sessionArr[] = sessionStr.split(",");
		String cutArr[] = cut.split("#");
		List cutList = new ArrayList();
		for (int i = 0; i < sessionArr.length; i++) {
			String tempCutArr[] = sessionArr[i].split("-");
			cutList.add(tempCutArr);
			if (timeStrToMinute(cutArr[1]) <= timeStrToMinute(tempCutArr[0])
					|| timeStrToMinute(cutArr[0]) >= timeStrToMinute(tempCutArr[1]))
				continue;
			if (timeStrToMinute(cutArr[0]) <= timeStrToMinute(tempCutArr[0])
					&& timeStrToMinute(cutArr[1]) >= timeStrToMinute(tempCutArr[1])) {
				cutList.remove(tempCutArr);
				continue;
			}
			if (timeStrToMinute(cutArr[0]) <= timeStrToMinute(tempCutArr[0])
					&& timeStrToMinute(cutArr[1]) > timeStrToMinute(tempCutArr[0])
					&& timeStrToMinute(cutArr[1]) < timeStrToMinute(tempCutArr[1])) {
				tempCutArr[0] = cutArr[1];
				continue;
			}
			if (timeStrToMinute(cutArr[0]) > timeStrToMinute(tempCutArr[0])
					&& timeStrToMinute(cutArr[0]) < timeStrToMinute(tempCutArr[1])
					&& timeStrToMinute(cutArr[1]) >= timeStrToMinute(tempCutArr[1])) {
				tempCutArr[1] = cutArr[0];
				continue;
			}
			if (timeStrToMinute(cutArr[0]) > timeStrToMinute(tempCutArr[0])
					&& timeStrToMinute(cutArr[1]) < timeStrToMinute(tempCutArr[1])) {
				tempCutArr[1] = cutArr[0];
				String addedArr[] = { cutArr[1], tempCutArr[1] };
				cutList.add(addedArr);
			}
		}

		String newAttdSession = "";
		for (Iterator i$ = cutList.iterator(); i$.hasNext();) {
			String cutArr1[] = (String[]) i$.next();
			newAttdSession = (new StringBuilder()).append(newAttdSession)
					.append(cutArr1[0]).append("-").append(cutArr1[1]).append(
							",").toString();
		}

		if (newAttdSession.length() > 0)
			newAttdSession.substring(0, newAttdSession.length() - 1);
		return newAttdSession;
	}

	public static long timeStrToMinute(String timeStr) {
		String timeArr[] = timeStr.split(":");
		return Long.parseLong(timeArr[0]) * 60L + Long.parseLong(timeArr[1]);
	}

	public static String getSessionTimeByExainDate(Date examinDate, Date date) {
		examinDate = DateUtil.parseDateByFormat(
				DateUtil.formatDate(examinDate), "yyyy-MM-dd");
		long minutes = (date.getTime() - examinDate.getTime()) / 60000L;
		long hours = minutes / 60L;
		long leftMinutes = minutes % 60L;
		String timeStr = (new StringBuilder()).append(hours).append(":")
				.append(leftMinutes).toString();
		return timeStr;
	}

	private static final String algorithm = "MD5";
}
